import {
  _decorator,
  Component,
  Node,
  RigidBody2D,
  Vec2,
  Animation,
  AnimationState,
  BoxCollider2D,
} from "cc";
const { ccclass, property } = _decorator;

@ccclass("EnemyControl")
export class EnemyControl extends Component {
  private _animationName = "airplane";

  speed = 20;

  protected start(): void {
    this._setLinearVelocity(0, this.speed * -1);

    this.node
      .getComponent(Animation)
      .on(
        Animation.EventType.FINISHED,
        (type: Animation.EventType, state: AnimationState) => {
          // console.log("动画结束", state);
          if (state.clip.name === this._animationName) {
            this.node && this.node.destroy();
          }
        }
      );
  }

  protected update(dt: number): void {
    if (this.node.position.y < -50) {
      this.node && this.node.destroy();
    }
  }

  die() {
    // 保证不会被子弹打多次, 先把碰撞组件移除了
    this.getComponent(BoxCollider2D).destroy();

    this._setLinearVelocity(0, 0);
    // 死亡的时候需要播放动画
    this.getComponent(Animation).play(this._animationName);
  }

  private _setLinearVelocity(x: number, y: number) {
    const rigidBody2D = this.getComponent(RigidBody2D);
    rigidBody2D.linearVelocity = new Vec2(x, y);
  }
}
